<template>
  <div id="user-order">
    <h2 class="title">我的订单</h2>
    <div v-if="orders.length === 0" class="no-orders">没有订单记录</div>
    <div v-else class="order-list">
      <el-collapse v-model="activeNames" @change="handleChange">
        <div v-for="order in orders" :key="order.id" class="order-container">
          <el-collapse-item :title="`订单号: ${order.id}`" :name="order.id">
            <div>
              <p>学生姓名: <strong>{{ order.student_name }}</strong></p>
              <p>班级: <strong>{{ order.class_name }}</strong></p>
              <p>学院: <strong>{{ order.college_name }}</strong></p>
              <p>学期: <strong>{{ order.semester_name }}</strong></p>
              <p>下单时间: <strong>{{ order.created_at }}</strong></p>
              <p>总金额: <strong>{{ order.total_amount }}元</strong></p>
              <p v-if="order.remark">备注: <strong>{{ order.remark }}</strong></p>
            </div>

            <div v-if="order.order_details && order.order_details.length > 0" class="order-books">
              <table>
                <thead>
                  <tr>
                    <th>书名</th>
                    <th>作者</th>
                    <th>类别</th>
                    <th>描述</th>
                    <th>价格</th>
                    <th>数量</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="book in order.order_details" :key="book.id">
                    <td>{{ book.materialInfo.name }}</td>
                    <td>{{ book.materialInfo.author }}</td>
                    <td>{{ book.materialInfo.category }}</td>
                    <td>{{ book.materialInfo.description }}</td>
                    <td>{{ book.materialInfo.price }}元</td>
                    <td>{{ book.quantity }}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div class="button-group">
              <button class="clear-button" @click="clearOrders(order.id)">清空此订单</button>
            </div>
          </el-collapse-item>
        </div>
      </el-collapse>
    </div>
  </div>
</template>
<script>
import { ref, onMounted, watch} from "vue";
import { ElMessage, ElNotification } from 'element-plus';
import axios from "axios";
import { useRoute } from 'vue-router';

export default {
  name: "UserOrder",
  setup() {
    const orders = ref([]);
    const activeNames = ref([]);
    const route = useRoute(); // 获取 route 对象

    const formatDateTime = (dateString) => {
      const date = new Date(dateString);
      const cstDate = new Date(date.getTime() + 8 * 60 * 60 * 1000); // 加8小时
      const year = cstDate.getFullYear();
      const month = String(cstDate.getMonth() + 1).padStart(2, '0');
      const day = String(cstDate.getDate()).padStart(2, '0');
      const hours = String(cstDate.getHours()).padStart(2, '0');
      const minutes = String(cstDate.getMinutes()).padStart(2, '0');
      const seconds = String(cstDate.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const fetchLearningMaterialInfo = async (learningMaterialId) => {
      try {
        const response = await axios.get(`/api/v1/learning_material/info`, {
          params: { id: learningMaterialId }
        });
        if (response.data.code === 200) {
          return response.data.data; // 返回图书详细信息
        } else {
          console.error("获取图书信息失败:", response.data.msg);
          return null;
        }
      } catch (error) {
        console.error(`获取图书信息 ${learningMaterialId} 的详细信息失败:`, error);
        return null;
      }
    };

    const fetchOrderDetails = async (order) => {
      try {
        const response = await axios.get(`/api/v1/order/info`, {
          params: { id: order.id }
        });
        if (response.data.code === 200) {
          const orderDetails = response.data.data;
          const learningMaterials = await Promise.all(orderDetails.order_details.map(async (detail) => {
            const materialInfo = await fetchLearningMaterialInfo(detail.learning_material_id);
            return { ...detail, materialInfo };
          }));
          return { ...order, order_details: learningMaterials };
        } else {
          console.error("获取订单详细信息失败:", response.data.msg);
          return order;
        }
      } catch (error) {
        console.error(`获取订单 ${order.id} 的详细信息失败:`, error);
        return order;
      }
    };


    const fetchOrders = async () => {
      try {
        const response = await axios.get("/api/v1/order/list_self");
        if (response.data && Array.isArray(response.data.data)) {
          const ordersList = response.data.data;
          const ordersWithDetails = await Promise.all(ordersList.map(order => fetchOrderDetails(order)));
          orders.value = ordersWithDetails.map(order => ({
            ...order,
            showDetails: false,
            created_at: formatDateTime(order.created_at)
          }));
          activeNames.value = ordersWithDetails.map(order => order.id);
        } else {
          console.error("后端接口未返回正确的数据格式");
        }
      } catch (error) {
        console.error("获取订单信息失败:", error);
      }
    };

    const clearOrders = async (orderId) => {
      try {
        const response = await axios.post(`/api/v1/order/delete`, {
          id: orderId
        }, {
          headers: {
            "Content-Type": "application/json",
          },
          withCredentials: true,
        });
        if (response.data.code === 200) {
          console.log("订单已清空");
          // 从订单列表中移除该订单
          const index = orders.value.findIndex(order => order.id === orderId);
          if (index !== -1) {
            orders.value.splice(index, 1);
          }
          activeNames.value = activeNames.value.filter(id => id !== orderId.toString());
          ElMessage({
            message: '订单删除成功',
            type: 'success',
          });
        }
      } catch (error) {
        console.error("订单创建失败:", error);
        ElNotification({
          title: '错误',
          message: `订单创建失败: ${error.message}`,
          type: 'error',
        });
      }
    };

    onMounted(() => {
      fetchOrders();
    });
     // 监听路由参数的变化
    watch(() => route.params.refresh, (newValue) => {
      if (newValue) {
        fetchOrders(); // 路由参数变化时重新获取订单
      }
    });

    return {
      orders,
      activeNames,
      formatDateTime,
      fetchOrderDetails,
      clearOrders,
      handleChange: (val) => {
        console.log(val);
      }
    };
  },
};
</script>


<style>
#user-order {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.no-orders {
  font-size: 18px;
  color: #888;
  text-align: center;
  margin-top: 20px;
}

.order-list {
  display: flex;
  flex-direction: column;
}

.order-container {
  border: 1px solid #ffffff;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #ffffff;
  border-radius: 6px;
  transition: box-shadow 0.3s;
}

.order-container:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.order-number {
  font-size: 18px;
  font-weight: bold;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.toggle-button {
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.toggle-button:hover {
  background-color: #66b1ff;
}

.clear-button {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.clear-button:hover {
  background-color: #ff7875;
}

.order-books {
  margin-top: 15px;
}

.book-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
  
}
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

tr:hover {
  background-color: #f1f1f1;
}
</style>
